<?php


namespace App\Http\Controllers\Admin;


use App\Model\Category;
use App\Tool\Json;

class CategoryController extends AuthCheckController
{


    function categoryList(){

        $pid=request()->input('pid',0);


        return Json::code(1,'success',$this->c($pid));
    }


    private function c($pid){

        static $all=[];

        $list=Category::where('pid',$pid)->get();

        if($list) {

            foreach ($list as $key => $value) {

                $all[] = $value;

                $id = $value->id;

                $this->c($id);


            }

        }

        return array_values($all);

    }


    function categoryUpdate(){

        $post=request()->post();

        $id=$post['id']??null;

        if(!$id&&!$post['lv']??null) $post['lv']=1;

        $post['img']=$post['img']?:'';

        Category::updateOrCreate(['id'=>$id],$post);


        return Json::code(1,'success');

    }

    function categoryDelete(){

        $id=request()->post('id',0);

        if(!$id) return Json::code(2,'id不存在！');

        $re=Category::where('pid',$id)->first();

        if($re) return Json::code(2,'无法删除,该分类下有其他子分类!');



        Category::destroy($id);

        return Json::code('1','success');

    }

}
